﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Prism.WebBuilder.Processors.Base;
using System.IO;
using Prism.WebBuilder.Lib.Cui;
using System.Text.RegularExpressions;

namespace Prism.WebBuilder.Processors
{
	public class Merge : ProcessorBase, IObject
	{
		private List<ISource> _fromList;
		private List<ReplaceItem> _replaces;
		private string _outputPath;

		public Merge()
		{
			_fromList = new List<ISource>();
			_replaces = new List<ReplaceItem>();
		}

		public Merge Init(string outputPath)
		{
			RegisterObject(outputPath, this);
			_outputPath = outputPath;
			return this;
		}

		public Merge From(string name)
		{
			IObject obj = GetObject(name);
			if (obj is ISource)
				From(obj as ISource);
			return this;
		}
		public Merge From(ISource source)
		{
			_fromList.Add(source);
			return this;
		}

		public Merge Replace(string replacePattern, string replaceString)
		{
			_replaces.Add(new ReplaceItem { ReplacePattern = replacePattern, ReplaceString = replaceString });
			return this;
		}

		public override void Process()
		{
			Cui.Info("merging to {0} ...", _outputPath);
			using (Cui.BeginIndent())
			{
				using (var writer = new StreamWriter(ResolvePath(_outputPath), false, Encoding.UTF8))
				{
					foreach (var source in _fromList)
					{						
						foreach (var item in source.GetItems())
						{
							if (item is ITextContentProvider)
							{
								writer.Write(processTextContent((item as ITextContentProvider).TextContent));
								Cui.Info("* {0}", item.Name);
							}
						}
					}
				}
			}
		}

		public void Trace(TracingOptions options)
		{
		}

		private string processTextContent(string content)
		{
			foreach (var replace in _replaces)
			{
				content = Regex.Replace(content, replace.ReplacePattern, replace.ReplaceString);
			}

			return content;
		}

		#region Internal classes
		class ReplaceItem
		{
			public string ReplacePattern { get; set; }

			public string ReplaceString { get; set; }
		}
		#endregion
	}
}
